﻿//////////////////////////////////////////////////////////////////
//
// ArchiveCollection.cs
//
// Copyright (c) 2012 Dan Pike. All rights reserved
//
// Refer to license.txt for any license restrictions.
// 
using Logger4Net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Utilities
{
   public abstract class ArchiveCollection<T> : ConfigurationElementCollection where T : ConfigurationElement, new()
   {
      //////////////////////////////////////////////////////////////////////////
      //
      public ArchiveCollection()
      {
         properties_ = new ConfigurationPropertyCollection();
      }

      //////////////////////////////////////////////////////////////////////////
      //
      protected override ConfigurationPropertyCollection Properties
      {
         get { return properties_; }
      }

      public override ConfigurationElementCollectionType CollectionType
      {
         get { return ConfigurationElementCollectionType.BasicMap; }
      }

      public void Clear()
      {
         base.BaseClear();
      }

      public void Add(T element)
      {
         base.BaseAdd(element);
      }

      public void Remove(T element)
      {
         base.BaseRemove(GetElementKey(element));
      }

      public string GetKey(int index)
      {
         return (string)base.BaseGetKey(index);
      }

      public T this[int index]
      {
         get { return (T)base.BaseGet(index); }
         set
         {
            if (null != base.BaseGet(index))
            {
               base.BaseRemoveAt(index);
            }
            base.BaseAdd(index, value);
         }
      }

      public new T this[string name]
      {
         get
         {
            T result = (T)base.BaseGet(name);
            if (null == result)
            {
               result = create(name) as T;
               base.BaseAdd(result);
            }
            return result;
         }
      }

      //////////////////////////////////////////////////////////////////////////
      //
      protected abstract ConfigurationElement create(string name);

      //////////////////////////////////////////////////////////////////////////
      //
      protected override ConfigurationElement CreateNewElement()
      {
         return create(string.Empty);
      }

      //////////////////////////////////////////////////////////////////////////
      //
      private static Logger logger_ = new Logger(typeof(ArchiveCollection<T>));
      private ConfigurationPropertyCollection properties_;
   }
}
